Page({
  data: {
    cameraContext: null,
    isDevtools: false,
    cameraUnavailable: false
  },

  onLoad() {
    const sys = wx.getSystemInfoSync();
    const isDevtools = sys && sys.platform === 'devtools';
    this.setData({ isDevtools, cameraUnavailable: false });
    // 尝试创建摄像头上下文；若在开发者工具失败则走兜底
    try {
      this.cameraContext = wx.createCameraContext();
    } catch (e) {
      console.warn('创建摄像头上下文失败，启用兜底模式', e);
      this.setData({ cameraUnavailable: true });
    }
  },

  onShow() {
    this.ensureCameraPermission();
  },

  ensureCameraPermission() {
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.camera']) {
          wx.authorize({
            scope: 'scope.camera',
            fail: () => {
              wx.showToast({ title: '请在设置中开启摄像头权限', icon: 'none' });
              this.setData({ cameraUnavailable: true });
            }
          });
        }
      }
    });
  },

  goBack() {
    const pages = getCurrentPages();
    if (pages && pages.length > 1) {
      wx.navigateBack({ delta: 1 });
    } else {
      // 没有上一个页面（直接打开或重启后进入），回到首页
      wx.reLaunch({ url: '/pages/index/index' });
    }
  },

  onCameraError(e) {
    console.error('摄像头错误', e);
    this.setData({ cameraUnavailable: true });
    wx.showToast({ title: '摄像头启动失败，可用相册/模拟拍照', icon: 'none' });
  },

  takePhoto() {
    if (!this.data.cameraContext) {
      this.setData({ cameraContext: wx.createCameraContext() });
    }
    this.data.cameraContext.takePhoto({
      quality: 'high',
      success: (res) => {
        const img = res.tempImagePath || '';
        wx.navigateTo({ url: `/pages/isbn-input/isbn-input?img=${encodeURIComponent(img)}` });
      },
      fail: (err) => {
        console.error('拍照失败', err);
        // 在开发者工具或摄像头不可用时，自动走模拟拍照兜底
        if (this.data.isDevtools || this.data.cameraUnavailable) {
          this.simulatePhoto();
        } else {
          wx.showToast({ title: '拍照失败', icon: 'none' });
        }
      }
    });
  },

  simulatePhoto() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album'],
      success: (res) => {
        const file = res.tempFiles && res.tempFiles[0];
        const img = file ? file.tempFilePath : '';
        if (!img) {
          wx.showToast({ title: '未获取到图片', icon: 'none' });
          return;
        }
        wx.navigateTo({ url: `/pages/isbn-input/isbn-input?img=${encodeURIComponent(img)}` });
      },
      fail: (err) => {
        if (String(err.errMsg).includes('cancel')) return;
        wx.showToast({ title: '选择图片失败', icon: 'none' });
      }
    });
  },

  chooseFromAlbum() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album'],
      success: (res) => {
        const file = res.tempFiles && res.tempFiles[0];
        const img = file ? file.tempFilePath : '';
        wx.navigateTo({ url: `/pages/isbn-input/isbn-input?img=${encodeURIComponent(img)}` });
      },
      fail: (err) => {
        if (String(err.errMsg).includes('cancel')) return;
        wx.showToast({ title: '未获取到图片', icon: 'none' });
      }
    });
  }
});